from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from .models import Category, CategoryImage, CategoryJson
from .serializers import (
    CategorySerializer,
    CategoryImageSerializer,
    CategoryJsonSerializer,
)


@api_view()
def get_server_status(request):
    return Response({"code": 0, "data": "", "message": "Server Online"})


class CategoryViewSet(ModelViewSet):
    queryset = Category.objects.prefetch_related("images", 'json_files').order_by("id").all()
    serializer_class = CategorySerializer

    def create(self, request, *args, **kwargs):
        data = request.data.copy()
        # 如果没有提供 creator
        if data.get('creator') is None:
            data["creator"] = request.user.id
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(
            serializer.data, status=status.HTTP_201_CREATED, headers=headers
        )


class CategoryImageViewSet(ModelViewSet):
    serializer_class = CategoryImageSerializer

    def get_serializer_context(self):
        return {"category_id": self.kwargs["category_pk"]}

    def get_queryset(self):
        return CategoryImage.objects.filter(category_id=self.kwargs["category_pk"])


class CategoryJsonViewSet(ModelViewSet):
    serializer_class = CategoryJsonSerializer

    def get_serializer_context(self):
        return {"category_id": self.kwargs["category_pk"]}

    def get_queryset(self):
        return CategoryJson.objects.filter(category_id=self.kwargs["category_pk"])
